package com.linkage.seapeak.base;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.bean.TokenInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.SignUtil;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.imp.GetTokenImp;
import com.linkage.seapeak.utils.CommonUtils;
import com.linkage.seapeak.utils.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaseActivity extends AppCompatActivity {

    public String TAG = "";

    private ShapeLoadingDialog shapeLoadingDialog;

    private String phone;

    public void SetPhone(String p)
    {
        phone = p;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setStatusBarMode(false);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        setStatusBarMode(true);

        Window window = getWindow();

        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

        //设置状态栏字体颜色为黑色
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);


        //设置状态栏字体颜色为白色
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    }

    public int dp2px(float dp) {
        return CommonUtils.dp2px(this, dp);
    }

    public void showToast(String msg) {
        ToastUtil.getInstance(this).showShortToast(msg);
    }

    public void showToast(String msg, ToastUtil.TOAST_TYPE toast_type) {
        ToastUtil.getInstance(this).showToast(msg, toast_type);
    }

    /**
     * 获取公用参数
     * @return
     */
    public FormBody.Builder getTokenRequest() {
        return new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", new Random().nextLong() + "")
                .add("timestamp", System.currentTimeMillis() + "")
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("source", "0");
    }

    /**
     * 设置状态栏模式
     * @param isPrimaryColor
     */
    public void setStatusBarMode(boolean isPrimaryColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (isPrimaryColor) {
                getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            } else {
                getWindow().setStatusBarColor(getResources().getColor(R.color.white));
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }
        }
    }

    public void showProgress(String string) {
        if (shapeLoadingDialog != null && shapeLoadingDialog.getDialog().isShowing())
            shapeLoadingDialog.dismiss();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        shapeLoadingDialog.setLoadingText(string);
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
    }
    public void showProgress() {
        showProgress("加载中...");
    }

    public void hideProgress() {
        if (shapeLoadingDialog!= null && shapeLoadingDialog.getDialog().isShowing())
            shapeLoadingDialog.dismiss();
    }

    /**
     * token获取
     * @param imp
     */
    public void getToken(final GetTokenImp imp) {
        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong() + "";
        String timestamp = System.currentTimeMillis() + "";
        params.put("appid", Consts.APPID);
        params.put("nonce", rom);
        params.put("timestamp", timestamp);

        String sign = SignUtil.createSign(Consts.APPKEY, params);

        RequestBody requestBody = new FormBody.Builder()
                .add("appid", "1000000001")
                .add("nonce", rom)
                .add("timestamp", timestamp)
                .add("sign", sign)
                .build();

        String url = Consts.WEBURL_GETTOKEN;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (imp != null)
                    imp.onFailed();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("code") == 0) {
                        Gson gson = new Gson();
                        TokenInfo info = gson.fromJson(object.optString("data"), TokenInfo.class);
                        BankruptcyApp.tokeninfo = info;
                        SPUtils.getInstance(Consts.SPNAME).put("tokeninfo", object.optString("data"));
                        if (imp != null)
                            imp.onSuccess();
                        return;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                if (imp != null)
                    imp.onFailed();
            }
        });
    }

    /**
     * 右上角菜单 可以是文字与图标
     */
    public class MenuAction {
        View.OnClickListener clickListener;
        String menuText;
        int menuIconRes;

        public MenuAction(View.OnClickListener clickListener, String menuText, int menuIconRes) {
            this.clickListener = clickListener;
            this.menuText = menuText;
            this.menuIconRes = menuIconRes;
        }
    }

    protected String getUserToken(){
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        return userToken;
    }

    public static final int REQUEST_CALL_PERMISSION = 10111; //拨号请求码
    public static final int REQUEST_SMS_PERMISSION = 10112; //拨号请求码

    /**
     * 判断是否有某项权限
     * @param string_permission 权限
     * @param request_code 请求码
     * @return
     */
    public boolean checkReadPermission(String string_permission,int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(this, string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(this, new String[]{string_permission}, request_code);
        }
        return flag;
    }

    /**
     * 检查权限后的回调
     * @param requestCode 请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CALL_PERMISSION: //拨打电话
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(this,"请允许拨号权限后再试",Toast.LENGTH_SHORT).show();
                } else {//成功
//                    call("tel:"+"10086");
                    Intent intent1 = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent1.setData(data);
                    startActivity(intent1);

                }
                break;
            case REQUEST_SMS_PERMISSION:
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(this,"请允许拨号权限后再试",Toast.LENGTH_SHORT).show();
                } else {//成功
//                    call("tel:"+"10086");
                    Intent intent1 = new Intent(Intent.ACTION_CALL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent1.setData(data);
                    startActivity(intent1);

                }
                break;
        }
    }
}
